<template>
  <el-dialog title="批量导入" :close-on-click-modal="false" :visible.sync="visible" class="cu-dialog cu-dialog_center cu-dialog-import" lock-scroll width="1000px">
    <el-steps :active="active" align-center>
      <el-step title="上传文件"></el-step>
      <el-step title="数据预览"></el-step>
      <el-step title="导入数据"></el-step>
    </el-steps>
    <div class="import-main" v-show="active == 1">
      <div class="upload">
        <div class="up_left">
          <img src="@/assets/images/upload.png" />
        </div>
        <div class="up_right">
          <p class="title">上传填好的数据表</p>
          <p class="tip">文件后缀名必须是xls或xlsx，文件大小不超过500KB，最多支持导入1000条数据</p>
          <el-upload :action="define.comUrl + '/api/campus/insurance/Uploader'" :headers="{ Authorization: $store.getters.token }" :on-success="handleSuccess" :on-remove="handleRemove" :before-remove="beforeRemove" :on-change="handleChange" :file-list="fileList" accept=".xls,.xlsx" :before-upload="beforeUpload" class="upload-area">
            <el-button type="text">上传文件</el-button>
          </el-upload>
        </div>
      </div>
      <div class="upload">
        <div class="up_left">
          <img src="@/assets/images/import.png" />
        </div>
        <div class="up_right">
          <p class="title">填写导入数据信息</p>
          <p class="tip">请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除</p>
          <el-button type="text" @click="templateDownload">下载模板</el-button>
        </div>
      </div>
    </div>
    <div class="import-main" v-show="active == 2">
      <custom-table v-loading="listLoading" :data="list">
        <el-table-column prop="enCode" label="校区编码" width="150">
          <template slot-scope="scope">
            <el-input v-model="scope.row.enCode" />
          </template>
        </el-table-column>
        <el-table-column prop="shortName" label="校区简称" width="150">
          <template slot-scope="scope">
            <el-input v-model="scope.row.shortName" />
          </template>
        </el-table-column>
        <el-table-column prop="policyName" label="保险名称" width="150">
          <template slot-scope="scope">
            <el-select v-model="scope.row.policyName" placeholder="请选择保险名称" filterable clearable required :style="{ width: '100%' }">
              <el-option :key="item.enCode" :label="item.fullName" :value="item.enCode" v-for="item in policyNameOptions" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="policyNumber" label="投保单号" width="150">
          <template slot-scope="scope">
            <el-input v-model="scope.row.policyNumber" />
          </template>
        </el-table-column>
        <el-table-column prop="effectiveDate" label="生效日期" width="150">
          <template slot-scope="scope">
            <el-date-picker v-model="scope.row.effectiveDate" clearable required :style="{ width: '100%' }" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="expirationDate" label="到期日期" width="150">
          <template slot-scope="scope">
            <el-date-picker v-model="scope.row.expirationDate" clearable required :style="{ width: '100%' }" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="insuranceCompany" label="投保公司" width="150">
          <template slot-scope="scope">
            <el-select v-model="scope.row.insuranceCompany" placeholder="请选择投保公司" filterable clearable required :style="{ width: '100%' }">
              <el-option :key="item.enCode" :label="item.fullName" :value="item.enCode" v-for="item in insuranceCompanyOptions" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="备注" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.description" placeholder="请对投保信息其他相关信息进行备注" />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="50">
          <template slot-scope="scope">
            <el-button size="mini" type="text" class="cu-table-delBtn" @click="handleDel(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </custom-table>
    </div>
    <div class="import-main" v-show="active == 3">
      <div class="success" v-if="!result.resultType">
        <img src="@/assets/images/success.png" alt="" />
        <p class="success-title">批量导入成功</p>
        <p class="success-tip">您已成功导入{{ result.snum }}条数据</p>
      </div>
      <div class="unsuccess" v-if="result.resultType">
        <el-alert title="错误提醒：导入失败数据展示" type="warning" show-icon :closable="false" />
        <div class="upload error-show">
          <div class="up_left">
            <img class="" src="@/assets/images/tip.png" />
          </div>
          <div class="up_right">
            <p class="tip">
              正常数量条数：
              <el-link type="success" :underline="false">{{ result.snum }}条</el-link>
            </p>
            <p class="tip">
              异常数量条数：
              <el-link type="danger" :underline="false">{{ result.fnum }}条</el-link>
            </p>
          </div>
        </div>
        <p class="contips">以下文件数据为导入异常数据</p>
        <custom-table :data="resultList" height="280px">
          <el-table-column prop="enCode" label="校区编码" width="100" />
          <el-table-column prop="shortName" label="校区简称" width="100" />
          <el-table-column prop="policyName" label="保险名称" align="left">
            <template slot-scope="scope">
              {{ scope.row.policyName | dynamicCodeText(policyNameOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="policyNumber" label="投保单号" align="center" />
          <el-table-column prop="insuranceCompany" label="投保公司" align="left">
            <template slot-scope="scope">
              {{ scope.row.insuranceCompany | dynamicCodeText(insuranceCompanyOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="effectiveDate" label="投保日期" align="center" :formatter="custom.tableDateFormat" />
          <el-table-column prop="expirationDate" label="到期日期" align="center" :formatter="custom.tableDateFormat" />
          <el-table-column prop="createUserName" label="记录人" align="left" />
          <el-table-column prop="description" label="备注" width="200" show-overflow-tooltip />
        </custom-table>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel()" v-if="active == 1">取 消</el-button>
      <el-button @click="prev" v-if="active == 2">上一步</el-button>
      <el-button @click="next" type="primary" v-if="active < 3" :loading="btnLoading" :disabled="active == 1 && !fileName">下一步</el-button>
      <el-button @click="cancel(true)" type="primary" v-else>关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { TemplateDownload, ImportData, ImportPreview } from '@/api/extend/insurance'
export default {
  data() {
    return {
      visible: false,
      btnLoading: false,
      listLoading: false,
      fileName: '',
      fileList: [],
      active: 1,
      list: [],
      resultList: [],
      result: {
        resultType: 0,
        snum: 0,
        fnum: 0
      },
      policyNameOptions: [
        {
          enCode: '1',
          fullName: '三合一'
        },
        {
          enCode: '3',
          fullName: '公众责任险'
        },
        {
          enCode: '5',
          fullName: '公众责任险+雇主责任险'
        },
        {
          enCode: '6',
          fullName: '公众责任险+财产一切险'
        },
        {
          enCode: '7',
          fullName: '其他'
        }
      ],
      insuranceCompanyOptions: [
        {
          enCode: '1',
          fullName: '未办理'
        },
        {
          enCode: '2',
          fullName: '安亲保'
        },
        {
          enCode: '3',
          fullName: '放心保'
        },
        {
          enCode: '4',
          fullName: '平安保险'
        },
        {
          enCode: '5',
          fullName: '太平洋保险'
        },
        {
          enCode: '6',
          fullName: '中国人寿'
        },
        {
          enCode: '7',
          fullName: '阳光保险'
        },
        {
          enCode: '8',
          fullName: '其他'
        }
      ]
    }
  },
  methods: {
    prev() {
      if (this.active == 1) return
      this.active--
    },
    next() {
      if (this.active == 2) {
        if (!this.list.length) return this.$message({ message: '导入数据为空', type: 'warning' })
        this.btnLoading = true
        ImportData({ list: this.list })
          .then(res => {
            this.result = res.data
            this.resultList = res.data.failResult
            this.btnLoading = false
            this.active++
          })
          .catch(() => {
            this.btnLoading = false
          })
      }
      if (this.active == 1) {
        if (!this.fileList.length || !this.fileName) return this.$message({ message: '请先上传文件', type: 'warning' })
        this.btnLoading = true
        ImportPreview({ fileName: this.fileName })
          .then(res => {
            // 对返回的数据进行中文到编码的转换
            this.list = this.convertChineseToCode(res.data.dataRow)
            this.btnLoading = false
            this.active++
          })
          .catch(() => {
            this.btnLoading = false
          })
      }
    },
    cancel(isRefresh) {
      this.visible = false
      if (isRefresh) this.$emit('refresh')
    },
    init() {
      this.active = 1
      this.fileList = []
      this.fileName = ''
      this.visible = true
    },
    handleDel(index) {
      this.list.splice(index, 1)
    },
    templateDownload() {
      TemplateDownload().then(res => {
        this.custom.downloadFile(res.data.url)
      })
    },
    beforeUpload(file) {
      let isRightSize = file.size / 1024 < 500
      if (!isRightSize) this.$message.error(`文件大小不能超过500KB`)
      return isRightSize
    },
    handleRemove(file, fileList) {
      this.fileList = []
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`).then(() => {})
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-1)
    },
    handleSuccess(res, file, fileList) {
      if (res.code == 200) {
        this.fileList = fileList.slice(-1)
        this.fileName = res.data.name
      } else {
        this.fileList = fileList.filter(o => o.uid != file.uid)
        this.$message({ message: res.msg, type: 'error', duration: 1000 })
      }
    },

    /**
     * 将Excel中的中文值转换为编码值
     * @param {Array} dataRows - 原始数据行
     * @returns {Array} 转换后的数据行
     */
    convertChineseToCode(dataRows) {
      // 保险名称中文到编码的映射
      const policyNameMap = {
        三合一: '1',
        公众责任险: '3',
        '公众责任险+雇主责任险': '5',
        '公众责任险+财产一切险': '6',
        其他: '7'
      }

      // 投保公司中文到编码的映射
      const companyMap = {
        未办理: '1',
        安亲保: '2',
        放心保: '3',
        平安保险: '4',
        太平洋保险: '5',
        中国人寿: '6',
        阳光保险: '7',
        其他: '8'
      }

      // 遍历数据行进行转换
      return dataRows.map(row => {
        const convertedRow = { ...row }

        // 转换保险名称
        if (row.policyName && policyNameMap[row.policyName]) {
          convertedRow.policyName = policyNameMap[row.policyName]
        }

        // 转换投保公司
        if (row.insuranceCompany && companyMap[row.insuranceCompany]) {
          convertedRow.insuranceCompany = companyMap[row.insuranceCompany]
        }

        return convertedRow
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.import-main {
  .upload {
    display: flex;
    align-items: center;
    .up_left {
      img {
        width: 120px;
      }
    }
  }
}
</style>
